package cn.wolfcode.luowowo.listener;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.enum1.RedisKeys;
import cn.wolfcode.luowowo.redis.Service.IStatisVoRedisService;
import cn.wolfcode.luowowo.redis.Service.IUserInfoRedisService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.vo.StatisVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis数据初始化监听器
 * spring容器一准备好之后马上执行数据初始化逻辑
 * 将mongodb数据(vo)加载到redis中
 */
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStatisVoRedisService statisVoRedisService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //spring容器创建完成（aop ioc di）之后马上执行
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        //从mogondb中查询攻略明细,设置到攻略vo对象中
        List<Strategy> list = strategyService.list();
        //注意,在还没有进行持久化前,要设置如果key中有数据直接跳过,否则会造成数据覆盖
        for (Strategy strategy : list) {
            //创建key
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.id);
            if (!(redisTemplate.hasKey(key))){
                //创建vo对象
                StatisVo statisVo = new StatisVo();
                BeanUtils.copyProperties(strategy , statisVo);
                //id要自己设置
                statisVo.setStrategyId(strategy.getId());
                //将其设置进redis中
                statisVoRedisService.setStatisVo(statisVo);
            }
        }
        //用户收藏列表的初始化
        //从mogondb中查询用户
        List<UserInfo> users = userInfoService.list();
        //遍历
        for (UserInfo user : users) {
            //获取key
            String key = RedisKeys.STRATEGY_FAVORNUM.join(user.getId());
            List<String> stragys = user.getStraygys();
            String s = JSON.toJSONString(stragys);
            //将其设置进redies中
            template.opsForValue().set(key,s);
        }

    }
}
